import React, { useState } from 'react';
import { Button, Checkbox, Form, Input, App, Spin } from 'antd';
import loginStyle from "./login.module.css"
import * as api from "@/api/users"
import { connect } from "react-redux"
import userActionCreator from '@/store/actions/userAction';
import { useNavigate } from "react-router-dom"

//将dispatch方法映射到组件内
const mapDispatchToProps = (dispatch: any) => {
    return {
        setUserInfo(payload: any) {
            dispatch(userActionCreator('SET_USERINFO', payload))
        }
    }
}

const Login: React.FC<{ setUserInfo?: (payload: any) => void }> = (props) => {
    //控制加载动画
    let [loading, setLoading] = useState<boolean>(false)
    //全局提示
    const { message } = App.useApp()
    //编程式导航hook
    let navigate = useNavigate()
    // 表单校验通过,会回调这个onFinish
    const onFinish = async (values: any) => {
        // console.log('Success:', values);
        //打开加载动画
        setLoading(true)
        //发起登入请求
        try {
            let res: any = await api.loginApi(values.username, values.password);
            //关闭加载动画
            setLoading(false)
            if (!res.data.state) {
                //密码错误登入失败的情况
                message.error(res.data.msg)
                //弹框提示
                return
            }
            // console.log(res)
            // 存储token到sessionStorage
            sessionStorage.setItem('qf-token', res.data.token)
            // 存储userInfo到redux
            props.setUserInfo!(res.data.userInfo)
            navigate("/")
            message.success(res.data.msg)
        } catch (e) {
            console.log(e)
        }


    };
    //表单校验失败,执行这个回调
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };

    //用户名校验函数
    const validateUsername = (rule: any, value: string) => {
        //英文字母，数字，下划线或者短横线组成,，并且用户名长度为 6~16位。
        let partten = /^[a-zA-Z0-9-_]{3,16}$/
        if (value && partten.test(value)) {
            return Promise.resolve()
        } else {
            return Promise.reject('由字母,数字,下划线组成,长度3-16位')
        }
    }
    //密码校验函数

    const validatePassword = (rule: any, value: string) => {
        if (value && value.length >= 3) {
            return Promise.resolve()
        } else {
            return Promise.reject('密码长度不能小于3位')
        }
    }


    return (
        <Spin tip='正在登入...' spinning={loading} className={loginStyle['login-spin']}>
            <div className={loginStyle['login-body']}>
                <Form
                    name="loginForm"
                    labelCol={{ span: 6 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    className={loginStyle['login-container']}
                >
                    <Form.Item>
                        <h1 className={loginStyle.title}>万锋erp系统</h1>
                    </Form.Item>
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{ required: true, validator: validateUsername }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, validator: validatePassword }]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item name="remember" valuePropName="checked" wrapperCol={{ span: 24 }}>
                        <Checkbox>7天免登入</Checkbox>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4, span: 24 }}>
                        <Button type="primary"
                            className={loginStyle['login-button']}
                            htmlType="submit">
                            登入
                        </Button>
                    </Form.Item>
                </Form >
            </div>
        </Spin>
    );
};

export default connect(null, mapDispatchToProps)(Login)